package priorities;

import java.util.Collections;
import java.util.Vector;

import general.ChannelAgent;

public class MostSendingFirst extends PriorityManager {

	
	
	Vector<AgentMessages> messages;
	
	int barrier1;
	int barrier2;
	public MostSendingFirst(int n) {
		messages = new Vector<AgentMessages>();
		barrier1 = n/3;
		barrier2 = n*2/3;
	}
	
	@Override
	public synchronized void updatePriority(ChannelAgent agent) {
		AgentMessages am = new AgentMessages(agent.getAgentId(), agent.getNumMessages());
		messages.remove(am);
		messages.add(am);
		Collections.sort(messages);
		int i = messages.indexOf(am);
		if (i>barrier2){
			agent.setPriority(Thread.MAX_PRIORITY);
		} else if (i<barrier1){
			agent.setPriority(Thread.MIN_PRIORITY);
		} else {
			agent.setPriority(Thread.NORM_PRIORITY);
		}
	}
	
	private static class AgentMessages implements Comparable<AgentMessages>{
		long messages;
		byte id;
		public AgentMessages(byte id, long messages) {
			this.messages = messages;
			this.id = id;
		}
		
		@Override
		public boolean equals(Object other) {
			return ((AgentMessages)other).id == id;
		}

		@Override
		public int compareTo(AgentMessages other) {
			int i = new Long(messages).compareTo(other.messages);
			if (i == 0) return new Byte(id).compareTo(other.id);
			else return i;
			
		}
		
	}
	
}
